import tkinter as tk
from tkinter import messagebox
from tkinter import scrolledtext
from threading import Timer
from playsound import playsound
from PIL import Image, ImageTk  # Corrected import
from BackEnd import BackEnd, checkAccount, addUser
from Config import *
import os

# Constants
DataPath = os.path.join('data', '')

STATE_INIT = 1
STATE_SINGLE = 2
STATE_MULTI = 3
STATE_JUDGE = 4
STATE_DONE = 5

# Initialize data
dataList = BackEnd()  # 存储得到的考题

# Print initial data for verification
for i in range(5):
    print(dataList.SingleList[i]['参考答案'])

# Initialize image lists
im = [None] * 5
img = [None] * 5


def getCurrentPath():
    """ 获取当前路径，找寻用户信息表和题库 """
    path = os.getcwd()  # 当前工作路径
    return path


def list2str(changList) -> str:
    """ 为tkinter的varString显示处理准备，可以显示考生选择的选项 """
    res = ''.join(str(item) for item in changList)
    return res


class FrontEnd:
    """ 前端类，完成注册和答题两个界面和数据调用 """

    def __init__(self):
        self.state = STATE_INIT  # 有限状态机，完成题目衔接和变化
        self.count = 0  # 计数到第几道题了
        self.minute = 60
        self.second = 0  # 设定考试时间60min
        self.ans = []  # 存放考生的结果，确认后判断
        self.score = 0  # 分数
        self.loginWindow = tk.Tk()
        self.initialLoginWindow(self.loginWindow)

    def initialLoginWindow(self, window):
        """ Initialize the login window """
        # Example of initializing the login window (to be implemented)
        window.title("Login")
        window.geometry("400x300")
        tk.Label(window, text="Username").pack()
        tk.Entry(window).pack()
        tk.Label(window, text="Password").pack()
        tk.Entry(window, show='*').pack()
        tk.Button(window, text="Login", command=self.login).pack()
        window.mainloop()

    def login(self):
        """ Handle login action """
        self.loginWindow.destroy()
        self.mainWindow = tk.Tk()
        self.initialMainWindow(self.mainWindow)

    def initialMainWindow(self, mainWindow):
        """ Initialize main window and the window settings """
        self.width = mainWindow.winfo_screenwidth()
        self.height = mainWindow.winfo_screenheight()

        print('[Function: initialMainWindow]')
        mainWindow.geometry(f"{self.width}x{self.height}")
        mainWindow['bg'] = 'skyblue'  # background color
        mainWindow.title('考试系统答题界面')
        mainWindow.resizable(width=True, height=True)

        mainWindow.protocol('WM_DELETE_WINDOW', self.closeMainWindow)
        self.setMenu(mainWindow)
        # make Esc exit the program
        mainWindow.bind('<Escape>', lambda e: mainWindow.destroy())

        self.totalCount = dataList.Single.totalNum + dataList.Multi.totalNum + dataList.Judge.totalNum

        self.showInitFsm()
        self.watchDog()
        mainWindow.mainloop()

    def showInitFsm(self):
        nextState = STATE_SINGLE
        print('[Function: Init_fsm] startup')

        self.varScore = tk.StringVar()  # 已获得分数
        self.varScore.set(f"{self.score}/100")
        self.showScoreName = tk.Label(self.mainWindow, text='已获得分数： ',
                                      width=150, height=50, justify='left',
                                      anchor='nw', font=('微软雅黑', 18),
                                      fg='white', bg='grey')
        self.showScoreName.place(x=10, y=10, width=150, height=50)
        self.showScore = tk.Label(self.mainWindow, textvariable=self.varScore)
        self.showScore.place(x=10, y=70, width=150, height=50)
        self.varTimeLft = tk.StringVar()
        self.timeLeft = tk.Label(self.mainWindow, textvariable=self.varTimeLft)
        self.timeLeft.place(x=self.width - 200, y=70, width=150, height=50)

        self.showTimeLeft = tk.Label(self.mainWindow, text='剩余时间', width=150, height=50,
                                     justify='left', anchor='ne', font=('微软雅黑', 18),
                                     fg='white', bg='grey', padx=20, pady=10)
        self.showTimeLeft.place(x=self.width - 200, y=10, width=150, height=60)

        self.varButtonA = tk.StringVar()
        self.varButtonA.set(f"A. {dataList.SingleList[self.count % 10]['A']}")
        self.varButtonB = tk.StringVar()
        self.varButtonB.set(f"B. {dataList.SingleList[self.count % 10]['B']}")
        self.varButtonC = tk.StringVar()
        self.varButtonC.set(f"C. {dataList.SingleList[self.count % 10]['C']}")
        self.varButtonD = tk.StringVar()
        self.varButtonD.set(f"D. {dataList.SingleList[self.count % 10]['D']}")
        self.varButtonE = tk.StringVar()
        self.varButtonE.set('')

        self.buttonA = tk.Button(self.mainWindow, textvariable=self.varButtonA, command=self.buttonAFsm)
        self.buttonB = tk.Button(self.mainWindow, textvariable=self.varButtonB, command=self.buttonBFsm)
        self.buttonC = tk.Button(self.mainWindow, textvariable=self.varButtonC, command=self.buttonCFsm)
        self.buttonD = tk.Button(self.mainWindow, textvariable=self.varButtonD, command=self.buttonDFsm)
        self.buttonOK = tk.Button(self.mainWindow, text='确认', command=self.buttonOKFsm)  # 确认按钮，确认不再更改答案
        self.buttonA.place(x=100, y=400, width=750, height=50)
        self.buttonB.place(x=100, y=500, width=750, height=50)
        self.buttonC.place(x=100, y=600, width=750, height=50)
        self.buttonD.place(x=100, y=700, width=750, height=50)
        self.buttonOK.place(x=1000, y=400, width=300, height=50)

        self.varChoice = tk.StringVar()
        self.varChoice.set(list2str(self.ans))  # 显示考生选择的选项
        self.showChoice = tk.Label(self.mainWindow, textvariable=self.varChoice)
        self.showChoice.place(x=1000, y=600, width=150, height=50)
        self.subject = scrolledtext.ScrolledText(self.mainWindow, relief="solid")
        self.subject.place(x=self.width / 3, y=10)
        self.subject.insert('end', f"{self.count + 1}. {dataList.SingleList[self.count]['题目内容']}\n")

        self.count = 0
        print('[Function: Init_fsm] complicated')
        self.state = nextState

    def buttonAFsm(self):
        print('     [Event: buttonA clicked]')
        if self.state == STATE_SINGLE:  # 单选
            self.ans = ['A']
        elif self.state == STATE_MULTI:  # 多选
            if 'A' not in self.ans:
                self.ans.append('A')
                self.ans = sorted(self.ans)
            else:
                self.ans.remove('A')
        else:  # 判断题
            self.ans = ['对']
        self.varChoice.set(list2str(self.ans))

    def buttonBFsm(self):
        print('     [Event: buttonB clicked]')
        if self.state == STATE_SINGLE:  # 单选
            self.ans = ['B']
        elif self.state == STATE_MULTI:  # 多选
            if 'B' not in self.ans:
                self.ans.append('B')
                self.ans = sorted(self.ans)
            else:
                self.ans.remove('B')
                sorted(self.ans)
        else:
            self.ans = ['对']
        self.varChoice.set(list2str(self.ans))

    def buttonCFsm(self):
        print('     [Event: buttonC clicked]')
        if self.state == STATE_SINGLE:  # 单选
            self.ans = ['C']
        elif self.state == STATE_MULTI:  # 多选
            if 'C' not in self.ans:
                self.ans.append('C')
                self.ans = sorted(self.ans)
            else:
                self.ans.remove('C')
        else:
            self.ans = ['对']
        self.varChoice.set(list2str(self.ans))

    def buttonDFsm(self):
        print('     [Event: buttonD clicked]')
        if self.state == STATE_SINGLE:  # 单选
            self.ans = ['D']
        elif self.state == STATE_MULTI:  # 多选
            if 'D' not in self.ans:
                self.ans.append('D')
                self.ans = sorted(self.ans)
            else:
                self.ans.remove('D')
        else:
            self.ans = ['对']
        self.varChoice.set(list2str(self.ans))

    def buttonOKFsm(self):
        print('     [Event: buttonOK clicked]')
        self.count += 1
        if self.count >= self.totalCount:
            self.state = STATE_DONE
        elif self.count < dataList.Single.totalNum:
            self.state = STATE_SINGLE
        elif self.count < (dataList.Single.totalNum + dataList.Multi.totalNum):
            self.state = STATE_MULTI
        else:
            self.state = STATE_JUDGE

        self.varButtonA.set(f"A. {dataList.SingleList[self.count % 10]['A']}")
        self.varButtonB.set(f"B. {dataList.SingleList[self.count % 10]['B']}")
        self.varButtonC.set(f"C. {dataList.SingleList[self.count % 10]['C']}")
        self.varButtonD.set(f"D. {dataList.SingleList[self.count % 10]['D']}")
        self.subject.delete(1.0, tk.END)
        self.subject.insert('end', f"{self.count + 1}. {dataList.SingleList[self.count % 10]['题目内容']}\n")
        self.varChoice.set('')
        self.ans = []

    def watchDog(self):
        if self.minute > 0 or self.second > 0:
            if self.second > 0:
                self.second -= 1
            else:
                self.minute -= 1
                self.second = 59
            self.varTimeLft.set(f"{self.minute:02d}:{self.second:02d}")
            self.timer = Timer(1, self.watchDog)
            self.timer.start()
        else:
            self.state = STATE_DONE
            messagebox.showinfo('提示', '考试时间结束！')
            self.closeMainWindow()

    def closeMainWindow(self):
        print('[Function: closeMainWindow]')
        if self.state != STATE_DONE:
            if messagebox.askokcancel("退出", "确定要退出吗？"):
                self.mainWindow.destroy()
        else:
            self.mainWindow.destroy()

    def setMenu(self, window):
        print('[Function: setMenu]')
        menubar = tk.Menu(window)

        usermenu = tk.Menu(menubar, tearoff=0)
        usermenu.add_command(label='查看成绩', command=self.look_score)
        usermenu.add_separator()
        usermenu.add_command(label='退出', command=self.closeMainWindow)
        menubar.add_cascade(label='用户', menu=usermenu)

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label='关于', command=self.about)
        menubar.add_cascade(label='帮助', menu=helpmenu)

        window.config(menu=menubar)

    def look_score(self):
        messagebox.showinfo("成绩", f"您的成绩是：{self.score} 分")

    def about(self):
        messagebox.showinfo("关于", "这是一个简单的考试系统")


if __name__ == '__main__':
    frontEnd = FrontEnd()
